import {
  initSaveTopicTreeAssignOrganization,
  initSaveTopicTreeLinkageOrganization,
  saveCuesTopic,
  selectTopicManageSetting,
  sendMessageTopic,
} from '@/services/api/api-cues-topic';
import {
  CheckCircleOutlined,
  CheckCircleTwoTone,
  ExclamationCircleOutlined,
  PlusOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  ModalForm,
  ProFormCascader,
  ProFormDateTimePicker,
  ProFormRadio,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { useAccess } from '@umijs/max';
import { Avatar, Button, Cascader, Divider, message, Modal } from 'antd';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';
import React, { useRef, useState } from 'react';

interface AddTopicProps {
  onRefurbish: () => void;
}

const AddTopic: React.FC<AddTopicProps> = ({ onRefurbish }) => {
  const access = useAccess();

  const formRef = useRef<ProFormInstance>();

  /**
   * 推送单位数据
   */
  const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();

  /**
   * 联动单位数据
   */
  const [treeLinkageOrganizationData, setTreeLinkageOrganizationDataState] = useState<DataNode[]>();

  // /**
  //  * 行业
  //  */
  // const [industryIds, setIndustryIdsState] = useState<any[]>([]);

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  /**
   * 选题计划配置
   */
  const [settings, setSettingsDataState] = useState<CuesTopicData.TopicManageSetting>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization == 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 保存 推送 单位
   */
  const loadInitSaveTopicTreeAssignOrganization = async () => {
    try {
      const response = await initSaveTopicTreeAssignOrganization();
      if (response.code === 0) {
        setTreeAssignOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  /**
   * 加载 保存 联动 单位
   */
  const loadInitSaveTopicTreeLinkageOrganization = async () => {
    try {
      const response = await initSaveTopicTreeLinkageOrganization({});
      if (response.code === 0) {
        setTreeLinkageOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  // /**
  //  * 加载 行业 列表
  //  * @param key
  //  */
  // const loadCuesIndustryData = async () => {
  //   try {
  //     const response = await listCuesIndustry();

  //     setIndustryIdsState(
  //       response.data.map((item) => {
  //         return { label: item.name, value: item.id };
  //       }),
  //     );
  //   } catch (error) {}
  // };

  /**
   * 加载 选题计划配置
   * @param key
   */
  const loadCuesTopicManageSetting = async () => {
    try {
      const response = await selectTopicManageSetting();
      const { code, data } = response;
      if (code === 0) {
        setSettingsDataState(data);

        formRef.current?.setFieldsValue({
          manage: data.manage === 1,
        });
      }
    } catch (error) {}
  };

  /**
   * 级联组件 搜索筛选
   * @param inputValue
   * @param path
   * @returns
   */
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  const [isLinkage, setIsLinkageState] = useState<boolean>(false);

  return (
    <DrawerForm
      key="add_topic_drawer_form"
      title="创建选题计划"
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
      }}
      layout="horizontal"
      formRef={formRef}
      trigger={
        <Button key="create" type="primary">
          <PlusOutlined />
          创建选题计划
        </Button>
      }
      initialValues={{}}
      onOpenChange={(visible: boolean) => {
        if (visible) {
          loadCuesTopicManageSetting();
          //加载权限树请求网络
          loadInitSaveTopicTreeAssignOrganization();
          loadInitSaveTopicTreeLinkageOrganization();
          // loadCuesIndustryData();
          onRefurbish();
        } else {
          setTreeAssignOrganizationDataState([]);
          setTreeLinkageOrganizationDataState([]);
          // setIndustryIdsState([]);
          setIsLinkageState(false);
          formRef.current?.resetFields();
        }
      }}
      onValuesChange={(values) => {
        if (values.linkageOrganizationIds !== undefined) {
          setIsLinkageState(values.linkageOrganizationIds.length > 0);
        }
      }}
      submitter={{
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              key="button_release_state_discard"
              icon={<CheckCircleOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                const values = formRef.current?.getFieldsValue();

                if (values.grade === undefined) {
                  message.warning('请选择分类');
                  return;
                }

                if (
                  values.name === undefined ||
                  values.name.length === 0 ||
                  values.name.trim() === ''
                ) {
                  message.warning('请输入标题');
                  return;
                }

                // if (values.industryIds === undefined || values.industryIds.length === 0) {
                //   message.warning('请选择最少一个行业');
                //   return;
                // }

                // if (values.labels === undefined || values.labels.length === 0) {
                //   message.warning('请输入最少一个标签');
                //   return;
                // }

                if (
                  values.content === undefined ||
                  values.content.length === 0 ||
                  values.content.trim() === ''
                ) {
                  message.warning('请输入选题内容');
                  return;
                }

                if (values.deadlineTime === undefined) {
                  message.warning('截止时间');
                  return;
                }

                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <ModalForm
              key={'modal_form_release_state_discard'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
                onCancel: () => console.log('run'),
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async (values) => {
                props.submit();
                return true;
              }}
            />,
          ];
        },
      }}
      onFinish={async (values) => {
        if (values.grade === undefined) {
          message.warning('请选择分类');
          return;
        }
        if (values.name === undefined || values.name.length === 0 || values.name.trim() === '') {
          message.warning('请输入标题');
          return;
        }

        // if (values.industryIds === undefined || values.industryIds.length === 0) {
        //   message.warning('请选择最少一个行业');
        //   return;
        // }

        // if (values.labels === undefined || values.labels.length === 0) {
        //   message.warning('请输入最少一个标签');
        //   return;
        // }

        if (
          values.content === undefined ||
          values.content.length === 0 ||
          values.content.trim() === ''
        ) {
          message.warning('请输入选题内容');
          return;
        }

        if (values.deadlineTime === undefined) {
          message.warning('截止时间');
          return;
        }


        const response = await saveCuesTopic({
          ...values,
          createdSource: 1,
        });

        if (response.code === 0) {
          message.success('提交成功');
          Modal.confirm({
            title: '发布成功，是否要全局推送？',
            icon: <ExclamationCircleOutlined />,
            content: '全局推送：对所选用户组进行短信通知。',
            async onOk() {
              const pushBulletinResponse = await sendMessageTopic({ id: response.data });
              if (pushBulletinResponse.code === 0) {
                message.success('推送成功');
              }
            },
            onCancel() {},
          });
          onRefurbish();
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProFormRadio.Group
        name="grade"
        radioType="button"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                paddingRight: 4,
              }}
            >
              *
            </span>
            分类
          </>
        }
        onChange={(value) => {
          const grade = value.target.value;
          formRef.current?.setFieldsValue({
            grade: grade,
          });
        }}
        options={[
          {
            label: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Avatar style={{ backgroundColor: '#f50' }} icon={<UserOutlined />} size={20} />
                <span style={{ marginLeft: 5 }}>重大</span>
              </div>
            ),
            value: 1,
          },
          {
            label: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Avatar style={{ backgroundColor: '#ffd591' }} icon={<UserOutlined />} size={20} />
                <span style={{ marginLeft: 5 }}>重要</span>
              </div>
            ),
            value: 2,
          },
          {
            label: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Avatar style={{ backgroundColor: '#2db7f5' }} icon={<UserOutlined />} size={20} />
                <span style={{ marginLeft: 5 }}>一般</span>
              </div>
            ),
            value: 3,
          },
        ]}
        fieldProps={{
          style: {
            marginLeft: '28px',
          },
          buttonStyle: 'solid',
        }}
      />
      <ProFormText
        width="xl"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                paddingRight: 4,
              }}
            >
              *
            </span>
            标题
          </>
        }
        name="name"
        fieldProps={{
          allowClear: true,
          maxLength: 200,
          style: {
            marginLeft: '28px',
          },
        }}
      />
      {/* <ProFormSelect
        width="xl"
        name="industryIds"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            行业
          </>
        }
        options={industryIds}
        fieldProps={{
          mode: 'multiple',
          allowClear: true,
          style: {
            marginLeft: '28px',
          },
        }}
        extra={
          <span
            style={{
              marginLeft: '28px',
            }}
          >
            最少输入一个
          </span>
        }
      /> */}
      {/* <Form.Item
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            标签
          </>
        }
        name="labels"
        extra={
          <span
            style={{
              marginLeft: '28px',
            }}
          >
            最少输入一个
          </span>
        }
      >
        <TagGroup
          style={{
            marginLeft: '28px',
          }}
        />
      </Form.Item> */}
      <ProFormTextArea
        width="xl"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            选题内容
          </>
        }
        name="content"
        fieldProps={{
          rows: 6,
          allowClear: true,
          maxLength: 50000,
          placeholder: '请输入描述（支持换行输入）',
          showCount: true,
        }}
      />
      {/* <ProFormDateTimeRangePicker
        width="xl"
        name="deadlineTime"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            截止时间
          </>
        }
        extra="到达设定的截止时候后，系统会关闭上报渠道"
        fieldProps={{
          disabled: [true, false],
          ranges: {
            后3天: [dayjs(), dayjs().add(3, 'days')],
            后5天: [dayjs(), dayjs().add(5, 'days')],
            后7天: [dayjs(), dayjs().add(7, 'days')],
            后10天: [dayjs(), dayjs().add(10, 'days')],
            后15天: [dayjs(), dayjs().add(15, 'days')],
            后20天: [dayjs(), dayjs().add(20, 'days')],
            后30天: [dayjs(), dayjs().add(30, 'days')],
            后50天: [dayjs(), dayjs().add(50, 'days')],
            后90天: [dayjs(), dayjs().add(90, 'days')],
          },
          format: 'YYYY-MM-DD HH:mm',
        }}
      /> */}
      <ProFormDateTimePicker
        width="xl"
        name="deadlineTime"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            截止时间
          </>
        }
        extra="到达设定的截止时候后，系统会关闭该计划"
        fieldProps={{
          minDate: dayjs(),
          presets: [
            { label: '后3天', value: dayjs().add(3, 'd') },
            { label: '后5天', value: dayjs().add(5, 'd') },
            { label: '后7天', value: dayjs().add(7, 'd') },
            { label: '后10天', value: dayjs().add(10, 'd') },
            { label: '后15天', value: dayjs().add(15, 'd') },
            { label: '后20天', value: dayjs().add(20, 'd') },
            { label: '后30天', value: dayjs().add(30, 'd') },
            { label: '后50天', value: dayjs().add(50, 'd') },
            { label: '后90天', value: dayjs().add(90, 'd') },
          ],
          format: 'YYYY-MM-DD HH:mm:ss',
        }}
      />
      <ProFormCascader
        width="xl"
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            推送单位
          </span>
        }
        name="assignOrganizationIds"
        placeholder="选择单位"
        extra="不选择，默认推送给所有部门、区县等单位"
        fieldProps={{
          options: treeAssignOrganizationData,
          showSearch: { filter },
          multiple: true,
          removeIcon: false,
          allowClear: true,
          maxTagCount: 'responsive',
          showCheckedStrategy: Cascader.SHOW_CHILD,
        }}
      />
      <Divider />
      <ProFormCascader
        width="xl"
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            {access.线索征集x配置x管理员
              ? '协助单位'
              : access.线索征集x配置x部门需求者
              ? '协助媒体、单位'
              : access.线索征集x配置x媒体需求者
              ? '联动媒体'
              : '联动单位'}
          </span>
        }
        name="linkageOrganizationIds"
        placeholder="选择单位"
        extra={'联动媒体、部门看到该选题计划的所有征集线索'}
        fieldProps={{
          options: treeLinkageOrganizationData,
          showSearch: { filter },
          multiple: true,
          removeIcon: false,
          allowClear: false,
          maxTagCount: 'responsive',
          showCheckedStrategy: Cascader.SHOW_CHILD,
        }}
      />
      <ProFormTextArea
        hidden={!isLinkage}
        width="xl"
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            {access.线索征集x配置x管理员
              ? '协助描述'
              : access.线索征集x配置x部门需求者
              ? '协助描述'
              : access.线索征集x配置x媒体需求者
              ? '联动描述'
              : '联动描述'}
          </span>
        }
        name="linkageDescribes"
        fieldProps={{
          rows: 6,
          allowClear: true,
          maxLength: 50000,
          placeholder: '请输入描述（支持换行输入）',
          showCount: true,
        }}
        extra={
          access.线索征集x配置x管理员
            ? '用于协助需求描述'
            : access.线索征集x配置x部门需求者
            ? '用于协助需求描述'
            : access.线索征集x配置x媒体需求者
            ? '用于联动需求描述'
            : '用于联动需求描述'
        }
      />
      {!access.线索征集x配置x管理员 && settings?.manage === 1 && (
        <ProFormTextArea
          width="xl"
          label={
            <span
              style={{
                marginLeft: 11,
              }}
            >
              申请描述
            </span>
          }
          name="recordDescribes"
          fieldProps={{
            rows: 2,
            allowClear: true,
            maxLength: 50000,
            placeholder: '请输入描述（支持换行输入）',
            showCount: true,
          }}
          extra={'该描述仅供管理员审核使用，不会对外展示'}
        />
      )}
    </DrawerForm>
  );
};
export default AddTopic;
